<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'mold:keep:asdMoldKeep:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="ASD_MOLD_KEEP"
        completeText="提交"
        :loading="loadingRef"
        :auth="'mold:keep:asdMoldKeep:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMoldKeepAsdMoldKeepForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { AsdMoldKeep, asdMoldKeepSave, asdMoldKeepForm } from '/@/api/mold/keep/asdMoldKeep';
  import { BpmButton } from '/@/components/Bpm';
  import { empUserTreeData } from '/@/api/sys/empUser';
  import { officeTreeData } from '/@/api/sys/office';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('mold.keep.asdMoldKeep');
  const { showMessage } = useMessage();
  const record = ref<AsdMoldKeep>({} as AsdMoldKeep);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增保养记录') : t('编辑保养记录'),
  }));
  const bedit = ref<boolean>(true);
  const loadingRef = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('工装名称'),
      field: 'moldCode',
      fieldLabel: 'basMold.name',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        return {
          selectType: 'moldSelect',
          onSelect: async (values) => {
            console.log(values);
            formModel['moldCode'] = values[0].code;
            formModel['lastNum'] = values[0].lastNum;
            formModel['basMold.caddcode'] = values[0].caddcode;
          },
        };
      },
      required: true,
    },
    {
      label: t('工装编码'),
      field: 'basMold.caddcode',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('工装尾号'),
      field: 'lastNum',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      // required: true,
    },
    {
      label: t('保养时长'),
      field: 'keepTime',
      component: 'Input',
      componentProps: {
        placeholder: t('单位：小时'),
        addonAfter: '小时',
        disabled: true,
      },
    },
    {
      label: t('保养内容'),
      field: 'keepDesc',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      required: true,
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
    },
    {
      label: t('送保人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: t('模具保养人'),
      field: 'repairName',
      fieldLabel: 'empUser.userName',
      component: 'TreeSelect',
      componentProps: {
        // api: empUserTreeData,
        api: officeTreeData,
        allowClear: true,
        params: { isLoadUser: true, userIdPrefix: '' },
        canSelectParent: false,
        treeCheckable: false,
      },
    },
    {
      label: t('检验状态'),
      field: 'checkResult',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'repair_and_keep_status',
        allowClear: true,
        // disabled: bedit.value,
        disabled: bedit.value ? false : true,
      },
      required: true,
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    console.log(data);
    if (data.bedit == 'false') {
      bedit.value = false;
    }
    await resetFields();
    const res = await asdMoldKeepForm(data);
    record.value = (res.asdMoldKeep || {}) as AsdMoldKeep;
    record.value.__t = new Date().getTime();

    record.value.moldCode ? '' : (record.value.moldCode = data.code);
    record.value.basMold?.name ?? (record.value.basMold = { name: data.name });
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      // console.log('submit', params, data, record);
      const res = await asdMoldKeepSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
  async function handleBpmMyTask(record: Recordable) {
    const data = await bpmTaskDefForm({ formKey: 'ASD_MOLD_REPAIR', bizKey: record.id });
    if (data.result == 'true') {
      const url = data.pcUrl;
      const idx = url.indexOf('?');
      // component
      let component: ReturnType<typeof defineComponent>;
      const compStr = idx == -1 ? url : url.substring(0, idx);
      if (compStr && compStr != '') {
        const imp = dynamicImport(compStr);
        if (imp) component = createAsyncComponent(imp);
      }
      // params
      let params = {};
      const paramStr = idx == -1 ? '' : url.substring(idx + 1);
      if (paramStr && paramStr != '') {
        params = qs.parse(paramStr);
      }
      // open
      if (component) {
        inputFormComponent.value = component;
        inputFormVisible.value = true;
        setDrawerData(params);
      }
    } else {
      showMessage(data.message);
    }
  }
</script>
